package cn.itcast.tant_test;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;


@Slf4j(topic = "c.TestPool")
public class TestPool {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(8, 84, 1, TimeUnit.SECONDS, 160, new CallerRunsPolicy());
        while (true) {
            int taskNum = 100;
            int i1 = new Random().nextInt(10);
            if (i1 == 3) {
                taskNum = 1000;
            }
            for (int i = 0; i < taskNum; i++) {
                int finalI = i;
                threadPool.execute(() -> {
                    log.info("执行任务:【{}】", finalI);
                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }


    }


}


/**
 * 线程池类
 */
@Slf4j(topic = "c.ThreadPool")
class ThreadPool {
    //核心线程数
    private final int coreSize;
    //最大线程数
    private final int maxSize;
    //非核心线程空闲时间
    private final long keepAliveTime;
    //时间单位
    private final TimeUnit timeUnit;
    //队列容量
    private final int queueCapcity;
    //任务队列
    private BlockingQueue<Runnable> taskQueue;
    //拒绝策略
    private RejectPolicy<Runnable> rejectPolicy;
    //线程集合
    private final HashSet<Worker> workers = new HashSet<>();

    //锁
    private final ReentrantLock mainLock = new ReentrantLock();


    public ThreadPool(int coreSize, int maxSize, long keepAliveTime, TimeUnit timeUnit, int queueCapacity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.maxSize = maxSize;
        this.keepAliveTime = keepAliveTime;
        this.timeUnit = timeUnit;
        this.queueCapcity = queueCapacity;
        this.rejectPolicy = rejectPolicy;
        this.taskQueue = new BlockingQueue<>(queueCapacity);
    }

    //获取任务队列
    public BlockingQueue<Runnable> getTaskQueue() {
        return taskQueue;
    }


    //  执行任务
    public void execute(Runnable task) {
        try {
            mainLock.lock();
            //1.新建核心线程
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task, true);
                workers.add(worker);
                worker.start();
                log.debug("创建核心线程 {}", worker.getName());
                return;
            }

            //2.往队列里面放
            if (!taskQueue.isFull()) {
                taskQueue.put(task);
                return;
            }

            //3.创建非核心线程
            if (workers.size() < maxSize) {
                Worker worker = new Worker(task, false);
                workers.add(worker);
                worker.start();
                log.debug("创建非核心线程 {}", worker.getName());
                return;
            }

            //4.执行拒绝策略
            if (rejectPolicy == null) {
                rejectPolicy = new AbortPolicy();
            }
            rejectPolicy.reject(this, task);
        } finally {
            mainLock.unlock();
        }
    }


    class Worker extends Thread {

        //首次任务:创建worker是带进来的任务
        private Runnable firstTask;

        //是否是核心线程
        private final boolean isCore;


        public Worker(Runnable task, boolean isCore) {
            this.firstTask = task;
            this.isCore = isCore;
        }

        @Override
        public void run() {
            if (Objects.nonNull(firstTask)) {
                firstTask.run();
                firstTask = null;
            }

            while (true) {
                //每次循环，先将上次执行过了的任务置为null
                Runnable runnable = null;
                if (isCore) {
                    //核心线程阻塞获取
                    runnable = taskQueue.take();
                } else {
                    //非核心线程超时获取
                    runnable = taskQueue.poll(keepAliveTime, timeUnit);
                }
                if (Objects.nonNull(runnable)) {
                    runnable.run();
                    log.debug("执行任务 {}", runnable);
                } else {
                    //没有拿到任务，且是非核心线程，则移除
                    if (!isCore) {
                        break;
                    }
                }
            }
            //只有非核心线程才能跳出循环，跳出循环则表示该线程过了存活时间，可以移除
            try {
                mainLock.lock();
                try {
                    workers.remove(this);
                    log.debug("移除非核心线程：{}", this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } finally {
                mainLock.unlock();
            }
        }
    }
}

/**
 * 阻塞队列类
 *
 * @param <T>
 */
@Slf4j(topic = "c.TestPool")
class BlockingQueue<T> {
    //任务队列,保存任务
    private final Deque<T> queue = new ArrayDeque<>();
    //R锁
    private final ReentrantLock lock = new ReentrantLock();

    //条件变量-消费者
    private final Condition fullWait = lock.newCondition();
    //条件变量-生产者
    private final Condition emptyWait = lock.newCondition();

    //队列容量
    private final int capacity;

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public boolean isFull() {
        lock.lock();
        try {
            return queue.size() >= capacity;
        } finally {
            lock.unlock();
        }
    }

    //阻塞-入队
    public void put(T task) {
        try {
            lock.lock();
            while (queue.size() == capacity) {
                try {
                    log.debug("等待加入任务队列 {} ...", task);
                    fullWait.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("加入任务队列 {}", task);
            queue.addLast(task);
            emptyWait.signal();
        } finally {
            lock.unlock();
        }
    }


    //阻塞-出队
    public T take() {
        try {
            lock.lock();
            while (queue.isEmpty()) {
                try {
                    log.debug("等待获取任务...take");
                    emptyWait.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWait.signal();
            return t;

        } finally {
            lock.unlock();
        }
    }


    //带超时的阻塞-出队
    public T poll(long timeout, TimeUnit timeUnit) {
        try {
            lock.lock();
            long nanos = timeUnit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    // 返回值是剩余时间
                    if (nanos <= 0) {
                        return null;
                    }
                    log.debug("等待获取任务...poll");
                    nanos = emptyWait.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWait.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }
}


// 拒绝策略
@FunctionalInterface
interface RejectPolicy<T> {
    void reject(ThreadPool pool, T task);
}

class AbortPolicy implements RejectPolicy<Runnable> {

    @Override
    public void reject(ThreadPool pool, Runnable task) {
        throw new RejectedExecutionException("队列已满，任务被拒绝");

    }
}

@Slf4j
class DiscardPolicy implements RejectPolicy<Runnable> {
    @Override
    public void reject(ThreadPool pool, Runnable task) {
        log.debug("放弃任务：{}", task);
    }
}

@Slf4j
class CallerRunsPolicy implements RejectPolicy<Runnable> {
    @Override
    public void reject(ThreadPool pool, Runnable task) {
        log.warn("调用者线程执行任务：{}", task);
        task.run();
    }
}

@Slf4j
class DiscardOldestPolicy implements RejectPolicy<Runnable> {
    @Override
    public void reject(ThreadPool pool, Runnable task) {
        log.debug("丢弃最老的任务：{}", task);
        pool.getTaskQueue().take();
        pool.execute(task);
    }
}